#include "messageutil.h"

void MessageUtil::SendMessage(char* data, int PktTo, int MailTo, int MailFrom, 
								int MailType, int lock, int cond, int mvI, 
								int mvV){
	PacketHeader outPktHdr;
    MailHeader outMailHdr;

	outPktHdr.to = PktTo;
    outMailHdr.to = MailTo;
    outMailHdr.from = MailFrom;
	outMailHdr.messageType = MailType;
	outMailHdr.lockID = lock;
	outMailHdr.condID = cond;
	outMailHdr.mvIndex = mvI;
	outMailHdr.mvValue = mvV;
    outMailHdr.length = strlen(data) + 1;
	
	bool success = postOffice->Send(outPktHdr, outMailHdr, data); 

    if ( !success ) {
      printf("The postOffice Send failed. You must not have the other Nachos running. Terminating Nachos.\n");
      interrupt->Halt();
    }
}

int MessageUtil::ReceiveMessage(int MailTo){
	PacketHeader inPktHdr;
    MailHeader inMailHdr;
	char buffer[MaxMailSize];
	
	postOffice->Receive(MailTo, &inPktHdr, &inMailHdr, buffer);
    printf("Got \"%s\" in (addr %d box %d) from (addr %d box %d)\n",buffer,inPktHdr.to,inMailHdr.to,inPktHdr.from,inMailHdr.from);
    fflush(stdout);
	
	return inMailHdr.mvValue;
}
